#!/usr/bin/python
# -*- coding: utf-8 -*-

__all__ = [u'HandlerPart']

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################

from pylot.interfaces import (HandlerInterface)
from pylot.core import (check_type, Path)
from parameters import Parameters

class HandlerPart (HandlerInterface):
  def __init__ (self, plugin_path=None, plugin_id=None):
    if plugin_path is None : plugin_path = PLUGIN_PATH
    HandlerInterface.__init__(self, plugin_path, plugin_id)
    self._parameters = Parameters(parameter_file=None,
                                  parameters_format=u'pylot',
                                  database_file=None,
                                  database_format=u'csv')

    #### Database
    #print self.database_file, self.database_format
    if self.database_file:
      self.readDatabase(self.database_file, self.database_format)

    ### Parameters
    try :
      if self.parameters_file and self.parameters_file.isfile() :
        self.readParameters(self.parameters_file, self.parameters_format)
    except TypeError :#si parameters_file==None
      pass

    for method in (
                   '_addBlock',
                   '_addParameter',
                   'addBook',

                   'newParameter',
                   'upFromFile',
                   'importfile',
                   'exportfile',

                   # Parameters methods
                   'remove',
                   'getValue',
                   'setValue',
                   'updateValue',
                   'setParameter',
                   'getParameter',

                   # Dict methods
                   'clear',
                   'fromkeys',
                   'get',
                   'items',
                   'iteritems',
                   'iterkeys',
                   'itervalues',
                   'keys',
                   'pop',
                   'update',
                   'values',
                   ) :
      try:
        setattr(self, method, getattr(self._parameters, method))
      except AttributeError :
        pass

  def _getparameters_file(self):
    return self._parameters.parameters_file

  def _setparameters_file(self, value):
    self._parameters.parameters_file = Path(value)

  def _getparameters_format(self):
    return self._parameters.parameters_format

  def _setparameters_format(self, value):
    self._parameters.parameters_format = value

  def _getdatabase_file(self):
    return self._parameters.database_file

  def _setdatabase_file(self, value):
    self._parameters.database_file = Path(value)

  def _getdatabase_format(self):
    return self._parameters.database_format

  def _setdatabase_format(self, value):
    self._parameters.database_format = value

  parameters_file = property(fget=_getparameters_file, fset=_setparameters_file)
  parameters_format = property(fget=_getparameters_format, fset=_setparameters_format)
  database_file = property(fget=_getdatabase_file, fset=_setdatabase_file)
  database_format = property(fget=_getdatabase_format, fset=_setdatabase_format)

  data = property(fget=lambda self:self._parameters)

  def __getitem__(self, x):
    return self._parameters[x]

  def __len__(self):
    return len(self._parameters)

  def __setitem__(self, key, value):
    self._parameters[key] = value

  def _write(self, msg):
    msg += u'\n'
    self.io.write(msg)
    self.io.writeStatus(msg)

  def reloadDatabase(self):
    if self.database_file :
      self.readDatabase(self.database_file, self.database_format)

  def saveAll(self):
    self.saveDatabase()
    self.saveParameters()

  def saveDatabase(self):
    if self.database_file :
      self.saveDatabaseAs(self.database_file, self.database_format)

  def saveDatabaseAs(self, dest, fmt=u'csv'):#alias
    u"""
    saves database as ... dest

    :param dest: out file path
    :type dest: str or :class:`~pylot.tools.Path`

    .. warning :: 
      
      'pylot' format for database is converted to 'csv' format 
      (default format for database)
    """
    if fmt.strip().lower() == u'pylot' :
      fmt = u'csv'
    self.exportfile(dest, fmt)
    self._write(self.tr_(u'Database saved to "%s"') % dest)

  def readDatabase(self, src, fmt=u'csv') :
    u"""
    Reads database file 'src'.

    :param src: parameter file path
    :type src: str or :class:`~pylot.tools.Path`    
    
    .. warning :: 
    
      'pylot' format for database is converted to 'csv' format 
      (default format for database)

    """
    check_type(u'src', src, [Path, unicode])
    self.database_format = fmt
    self.database_file = Path(src).abspath()
    if fmt.strip().lower() == u'pylot' :
      fmt = u'csv'
    self.importfile(src, fmt)
    self._write(self.tr_(u'Database file "%s" loaded') % src)

  def readParameters(self, src, fmt=u'pylot', only_existing_keys=True) :
    u"""
    Reads parameter file 'src'.

    :param src: parameter file path
    :type src: str or :class:`~pylot.tools.Path`
    """
    self.upFromFile(src, fmt, only_existing_keys)
    self._write(self.tr_(u'Database updated with "%s"') % src)
    #self._parameters.sortAll()

  def saveParameters(self):
    if self.parameters_file :
      self.saveParametersAs(self.parameters_file, self.parameters_format)

  def saveParametersAs(self, dest, fmt=u'pylot'):
    u"""
    saves parameters as ... dest

    :param dest: out file path
    :type dest: str or :class:`~pylot.tools.Path`
    """
    self.exportfile(dest, fmt)
    self._write(self.tr_(u'Parameters saved to "%s"') % dest)
